//
//  LNHGoodsDetailViewModel.m
//  LNH
//
//  Created by cruise on 2018/2/6.
//  Copyright © 2018年 twentylx. All rights reserved.
//

#import "LNHGoodsDetailViewModel.h"

NSString *kPropertyDataKeyGoodsDetailBannerUrl = @"kPropertyDataKeyGoodsDetailBannerUrl";

NSString *kPropertyDataKeyGoodsDetailSkuID = @"kPropertyDataKeyGoodsDetailSkuID";
NSString *kPropertyDataKeyGoodsDetailSkuName = @"kPropertyDataKeyGoodsDetailSkuName";
NSString *kPropertyDataKeyGoodsDetailSkuSpliceValue = @"kPropertyDataKeyGoodsDetailSkuSpliceValue";
NSString *kPropertyDataKeyGoodsDetailSkuValue = @"kPropertyDataKeyGoodsDetailSkuValue";
NSString *kPropertyDataKeyGoodsDetailSkuAttrValueList = @"kPropertyDataKeyGoodsDetailSkuAttrValueList";
NSString *kPropertyDataKeyGoodsDetailSkuAttrValueStringList = @"kPropertyDataKeyGoodsDetailSkuAttrValueStringList";

@interface LNHGoodsDetailViewModel()<LMBaseRequestFeformDelegate, YTKRequestDelegate>

@property (nonatomic, strong) NSString *goodsId;

@end

@implementation LNHGoodsDetailViewModel

- (instancetype)initWithParams:(NSDictionary *)params
{
    if (self = [super initWithParams:params]) {
        self.goodsId = self.params[@"goodsId"];
        NSLog(@"self.params:%@", self.params[@"goodsId"]);
        self.levelId = self.params[@"level"];
        
        if ([self.levelId isEqualToString:@""] || self.levelId == nil) {
            self.isUpgrade = NO;
        } else {
            self.isUpgrade = YES;
        }
        self.distristId = self.params[@"districtId"];
    }
    return self;
}

/**
 viewModel 初始化属性
 */
- (void)lm_initializeForViewModel
{
    self.hasVideo = NO;
    self.selectSkuList = [NSMutableArray new];
}

#pragma mark - Getter
- (RACCommand *) fetchGoodsDetailDataCommand
{
    if (!_fetchGoodsDetailDataCommand) {
        
        @weakify(self);
        _fetchGoodsDetailDataCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            
            LNHGoodsInfoAPI *goodsInfoAPI = [[LNHGoodsInfoAPI alloc] initWithGid:self.goodsId];
            // 数据返回值reformat代理
            NSLog(@"%@",self.goodsId);
            goodsInfoAPI.reformDelegate = self;
            // 数据请求响应代理 通过代理回调
            goodsInfoAPI.delegate = self;

            return [[[goodsInfoAPI rac_requestSignal] doNext:^(id  _Nullable x) {
                // 解析数据
            }] materialize];
        }];
    }
    return _fetchGoodsDetailDataCommand;
}

#pragma mark - LMBaseRequestFeformDelegate

- (id)request:(LMBaseRequest *)request reformJSONResponse:(id)jsonResponse
{
    
    NSLog(@"jsonResponse:%@", jsonResponse);
    
    if([request isKindOfClass:LNHGoodsInfoAPI.class]){
        // 在这里对json数据进行重新格式化
        
        //banner数据
        NSMutableArray *imageList = [NSMutableArray new];
        NSArray *itemImageList = jsonResponse[@"goods_images"];
        
        NSString *videoUrl = jsonResponse[@"video_url"];
        NSString *videoCoverUrl = jsonResponse[@"cover_url"];
        
        if (!IsStrEmpty(videoUrl)) {
            self.hasVideo = YES;
            
            NSDictionary *dict = @{ kPropertyDataKeyGoodsDetailBannerUrl: videoUrl,
                                    kPropertyDataKeyGoodsDetailVideoCoverUrl: videoCoverUrl
                                    };
            
            [imageList addObject:dict];
        }
        
        [itemImageList enumerateObjectsUsingBlock:^(NSString *shortUrlStr, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDictionary *dict = @{ kPropertyDataKeyGoodsDetailBannerUrl: [NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, shortUrlStr]
                                    };
            
            [imageList addObject:dict];
            
        }];
        
        self.goodsImageList = imageList;
        
        //产品参数展示数据
        
        NSMutableArray *itemSkuAttrList = [NSMutableArray new];
        NSMutableArray *itemParameterList = [NSMutableArray new];
        NSArray *itemAttrList = jsonResponse[@"sku_attr"];
        
        if (itemAttrList.count > 0) {
        __block NSString *name = @"";
        __block NSString *value = @"";
        
        [itemAttrList enumerateObjectsUsingBlock:^(NSArray *list, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDictionary *skuAttrDict0 = list[0];
            
            if (self.selectSkuList.count < itemAttrList.count) {
                [self.selectSkuList insertObject:skuAttrDict0[@"id"] atIndex:idx];
            }
            
            
            NSLog(@"selectSkuList:%@", self.selectSkuList);
            
            NSMutableArray *itemAttrValueList = [NSMutableArray new];
            NSMutableArray *itemAttrValueStringList = [NSMutableArray new];
            
            for (int i=0; i < list.count; i++) {
                NSDictionary *dict = list[i];
                name = dict[@"name"];
                
                if (i == list.count-1) {
                    value = [value stringByAppendingString:dict[@"attr_value"]];
                } else {
                   // value = [value stringByAppendingString:[NSString stringWithFormat:@"%@,", dict[@"attr_value"]]];
                     value = [value stringByAppendingString:[NSString stringWithFormat:@"%@", dict[@"attr_value"]]];
                }
                
                NSDictionary *itemAttrValueDict = @{
                                                    kPropertyDataKeyGoodsDetailSkuID: dict[@"id"],
                                                    kPropertyDataKeyGoodsDetailSkuValue: dict[@"attr_value"],
                                                    
                                                     };
                [itemAttrValueList addObject:itemAttrValueDict];
                [itemAttrValueStringList addObject:dict[@"attr_value"]];
                
                
            }
            
            NSDictionary *itemDict1 = @{
                                   kPropertyDataKeyGoodsDetailSkuName:name,
                                   kPropertyDataKeyGoodsDetailSkuSpliceValue:value
                                   };
            
            NSDictionary *itemDict2 = @{
                                       kPropertyDataKeyGoodsDetailSkuName:name,
                                       kPropertyDataKeyGoodsDetailSkuAttrValueList:itemAttrValueList,
                                       kPropertyDataKeyGoodsDetailSkuAttrValueStringList:itemAttrValueStringList
                                       };
            
            [itemSkuAttrList addObject:itemDict1];
            [itemParameterList addObject:itemDict2];
            
            name = @"";
            value = @"";
            
        }];
        
        
        self.skuAttrList = itemSkuAttrList;
        self.parameterList = itemParameterList;
        
        self.skuDict = jsonResponse[@"sku_list"];
        
        NSString *key = [self.selectSkuList componentsJoinedByString:@"-"];
        
        NSDictionary *selectSkuDict = self.skuDict[key];
        
        self.priceStr = [NSString stringWithFormat:@"￥:%@",selectSkuDict[@"price"]];
        self.stockStr = [NSString stringWithFormat:@"库存%@件",selectSkuDict[@"stock"]];
        self.stock = [selectSkuDict[@"stock"] integerValue];
        } else {
            self.priceStr = [NSString stringWithFormat:@"￥: %.2f", [jsonResponse[@"price"] doubleValue]];
            self.stockStr =  [NSString stringWithFormat:@"库存%@件", jsonResponse[@"stock"]];
            self.stock = [jsonResponse[@"stock"] integerValue];
        }
        
        //商品价格..等数据
        self.infoDict = @{
                 kPropertyDataKeyGoodsDetailID : jsonResponse[@"id"],
                 kPropertyDataKeyGoodsDetailName : jsonResponse[@"name"],
                 kPropertyDataKeyGoodsDetailPrice : [NSString stringWithFormat:@"￥: %.2f", [jsonResponse[@"price"] doubleValue]],
                 kPropertyDataKeyGoodsDetailPostage : [NSString stringWithFormat:@"快递: %.2f 元", [jsonResponse[@"postage"] doubleValue]],
                 kPropertyDataKeyGoodsDetailSales : [NSString stringWithFormat:@"月销: %@ 笔",  DecodeDefaultStrFromDic(jsonResponse, @"sales", @"0")],
                 kPropertyDataKeyGoodsDetailLocation : jsonResponse[@"site"],
                 kPropertyDataKeyGoodsDetailHtmlString : jsonResponse[@"detail"],
                 kPropertyDataKeyGoodsDetailStock : [NSString stringWithFormat:@"库存%@件", jsonResponse[@"stock"]],
                 kPropertyDataKeyGoodsDetailGoodsUrl : [NSString stringWithFormat:@"%@/%@", BASE_IMAGE_DOMAIN, jsonResponse[@"goods_img"]],
                 
                 
                 };
    }
    
    
    return jsonResponse;
}

#pragma mark - YTKRequestDelegate
- (void)requestFinished:(__kindof YTKBaseRequest *)request
{
    // 解析数据
    
    
}

- (void)requestFailed:(__kindof YTKBaseRequest *)request
{
    // do something
}

#pragma mark - Public

-(void) skuSelectedRow:(NSInteger)row atIndex:(NSUInteger)index {
    
    
    NSDictionary *dict = self.parameterList[row];
    NSArray *tags = dict[kPropertyDataKeyGoodsDetailSkuAttrValueList];
    NSString *skuID = tags[index][kPropertyDataKeyGoodsDetailSkuID];
    
    [self.selectSkuList replaceObjectAtIndex:row withObject:skuID];
    
    NSString *key = [self.selectSkuList componentsJoinedByString:@"-"];
    
    NSDictionary *selectSkuDict = self.skuDict[key];
    
    self.priceStr = [NSString stringWithFormat:@"￥:%@",selectSkuDict[@"price"]];
    self.stockStr = [NSString stringWithFormat:@"库存%@件",selectSkuDict[@"stock"]];
    self.stock = [selectSkuDict[@"stock"] integerValue];
//
//    NSLog(@"selectSkuList:%@", [self.selectSkuList componentsJoinedByString:@"-"]);
//    NSLog(@"_selectedRow:%ld,atIndex:%ld", row, index);
}

@end
